from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session,render_template

from info import constants, db
from info.models import User, Category, News
from info.utils.commons import login_required
from info.utils.response_code import RET
from . import news_blue


#首页模板数据加载
@news_blue.route('/')
@login_required
def index():
    user = g.user
    #新闻分类数据加载
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻分类数据失败')
    if not categories:
        return jsonify(errno=RET.NODATA,errmsg='无新闻分类数据')
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())
    #新闻点击排行加载
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻排行数据失败')
    if not news_list:
        return jsonify(errno=RET.NODATA,errmsg='无新闻数据排行')
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())


    data={
        'user_info':user.to_dict() if user else None,
        'category_list':category_list,
        'news_click_list':news_click_list
    }


    return render_template('news/index.html',data=data)

#项目favicon.ico文件的加载

@news_blue.route('/favicon.ico')
def favicon():
    #实现/favicon.ico路径下的加载
    return current_app.send_static_file('news/favicon.ico')



#获取新闻列表数据
@news_blue.route('/news_list')
def get_news_list():
    # 获取数据
    cid = request.args.get('cid','1')
    page = request.args.get('page','1')
    per_page = request.args.get('per_page','10')
    #转换参数类型
    try:
        cid,page,per_page = int(cid),int(page),int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数格式错误')
    #判断分类是不是最新
    filters = []
    if cid > 1:
        filters.append(News.category_id==cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻数据失败')
     #获取分页后的数据
    news_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())
    data = {
        'news_dict_list':news_dict_list,
        'total_page':total_page,
        'current_page':current_page
    }
    return jsonify(errno=RET.OK,errmsg='OK',data=data)


#加载新闻详情
@news_blue.route('/<int:news_id>')
@login_required
def get_news_detail(news_id):
    #从登陆验证装饰器中获取user信息
    user = g.user
    # 新闻点击排行加载

    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻排行数据失败')
    if not news_list:
        return jsonify(errno=RET.NODATA, errmsg='无新闻数据排行')
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())

    #新闻详情数据加载
    try:
        news=News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询新闻详情数据失败')
    if not news:
        return jsonify(errno=RET.NODATA,errmsg='无新闻详情数据')

    #收藏与取消收藏
    is_collected = False
    if news in g.user.collection_news:
        is_collected = True

    data = {
        'user_info': user.to_dict() if user else None,
        'news_click_list': news_click_list,
        'news_detail':news.to_dict(),
        'is_collected':is_collected
    }

    return render_template('news/detail.html',data=data)


@news_blue.route('/news_collect',methods=['POST'])
@login_required
def news_collect():
    user = g.user
    #判断用户是否登陆
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    #获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')
    #检查参数完整性
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    #转换newsid数据类型
    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数类型错误')
    #检查action参数的范围
    if action not in ['collect','cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数范围错误')
    #根据新闻id查询数据
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')
    #判断查询结果
    if not news:
        return jsonify(errno=RET.NODATA, errmsg='无新闻数据')
    #如果用户选的是收藏
    if action == 'collect':
        # 该新闻用户之前未收藏
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
        # 提交数据
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
        # 返回结果
    return jsonify(errno=RET.OK, errmsg='OK')






















